package taskdao

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"xr-game-server/core/cache"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/constants/db"
	"xr-game-server/entity"
)

var taskCache *cache.CacheMgr
var taskDetailCache *cache.CacheMgr
var resetTimeCache *cache.CacheMgr

func InitTask() {
	taskCache = cache.NewCacheMgr()
	taskDetailCache = cache.NewCacheMgr()
	resetTimeCache = cache.NewCacheMgr()
}

func GetTasksByRoleId(roleId uint64) []*entity.PlayerTask {
	data := taskCache.GetData(roleId, func(ctx context.Context) (value interface{}, err error) {
		tasks := make([]*entity.PlayerTask, common.Zero)
		g.Model(string(entity.TbPlayerTask)).Unscoped().Where(string(entity.PlayerTaskRoleId), roleId).Scan(&tasks)
		return tasks, nil
	})
	return data.([]*entity.PlayerTask)
}

func GetTaskByRoleIdAndTaskCfgId(roleId uint64, taskCfgId uint64) *entity.PlayerTask {
	for _, playerTask := range GetTasksByRoleId(roleId) {
		if playerTask.TaskCfgId == taskCfgId {
			return playerTask
		}
	}
	return nil
}

func GetTaskDetailByTaskId(taskId uint64) *entity.PlayerTaskDetail {
	for _, taskDetail := range GetTaskDetailsByTaskId(taskId) {
		if taskDetail.TaskId == taskId {
			return taskDetail
		}
	}
	return nil
}

func GetTaskDetailsByTaskId(taskId uint64) []*entity.PlayerTaskDetail {
	data := taskDetailCache.GetData(taskId, func(ctx context.Context) (value interface{}, err error) {
		taskDetails := make([]*entity.PlayerTaskDetail, common.Zero)
		g.Model(string(entity.TbPlayerTaskDetail)).Unscoped().Where(string(entity.PlayerTaskDetailTaskId), taskId).OrderAsc(string(entity.PlayerTaskDetailOrderIndex)).Scan(&taskDetails)
		return taskDetails, nil
	})
	return data.([]*entity.PlayerTaskDetail)
}

func AddTask(task *entity.PlayerTask) {
	lst := GetTasksByRoleId(task.RoleId)
	lst = append(lst, task)
	taskCache.FlushCache(task.RoleId, lst)
}
func AddTaskDetail(taskDetail *entity.PlayerTaskDetail) {
	lst := GetTaskDetailsByTaskId(taskDetail.TaskId)
	lst = append(lst, taskDetail)
	taskDetailCache.FlushCache(taskDetail.TaskId, lst)
}

func GetTaskResetTime(roleId uint64) *entity.PlayerTaskResetTime {
	data := resetTimeCache.GetData(roleId, func(ctx context.Context) (value interface{}, err error) {
		var resetTime *entity.PlayerTaskResetTime
		g.Model(string(entity.TbPlayerTaskResetTime)).Unscoped().Where(string(db.IdName), roleId).Scan(&resetTime)
		if resetTime == nil {
			resetTime = entity.NewPlayerTaskResetTime(roleId)
		}
		return resetTime, nil
	})
	return data.(*entity.PlayerTaskResetTime)
}
